package com.storlead.shiro.service.impl;

import com.storlead.shiro.mapper.UserInfoMapper;
import com.storlead.shiro.model.UserInfo;
import com.storlead.shiro.service.UserInfoService;
import com.storlead.shiro.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: Timo
 * @Date: 2019/2/13 11:16
 * @Description: 类用途：
 */
@Slf4j
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo findUser(Integer userId) {
        UserInfo userInfo = userInfoMapper.findUser(userId);
        return userInfo;
    }

    @Override
    public UserInfo findUser(String userName) {
        return userInfoMapper.findUserByName(userName);
    }

    @Override
    public UserInfo findUser(String userName, String passWord) {
        return userInfoMapper.findUserByNameAndPwd(userName,passWord);
    }

    @Override
    public Result login(UserInfo userInfo) {
        UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserName(),userInfo.getPassword());
        UserInfo currentLoginUser = findUser(userInfo.getUserName());
        if (currentLoginUser == null){
            return new Result(1,"该用户不存在");
        }
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        subject.getSession().setAttribute("USER_INFO",userInfo);

        return new Result(1,"登陆成功",userInfo,true,true);
    }

    @Override
    public void logout() {

    }
}
